<!DOCTYPE html>
<html lang="en">

<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    
        
                <meta name="keywords" content="爱前端 | 爱工作 | 爱生活">
                
                    
                            <meta name="description" content="This is My blog">
                            
                                <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
                                <title>
                                    
                                        vue单页面，多路由，前进刷新，后退不刷新 |
                                            
                                                一只正在成长的程序猿
                                </title>
                                
                                    <link rel="shortcut icon" href="/images/headPortrait.png">
                                    
                                        <link rel="stylesheet" href="/css/style.css">
                                            
                                                <link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">
                                                    
                                                        <script src="/js/pace.min.js"></script>
</head></html>

    <body>
        <main class="content">
            <section class="outer">
    <article id="post-keepAlive使用方法" class="article article-type-post" itemscope itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      vue单页面，多路由，前进刷新，后退不刷新
    </h1>
  
  




      </header>
    

    
      <div class="article-meta">
        <a href="/2019/08/07/keepAlive使用方法/" class="article-date">
  <time datetime="2019-08-07T09:31:46.484Z" itemprop="datePublished">2019-08-07</time>
</a>
        
  <div class="article-category">
    <a class="article-category-link" href="/categories/技术/">技术</a>
  </div>

      </div>
    

    <div class="article-entry" itemprop="articleBody">
      

      

      
        <blockquote>
<p>目的：vue-cli构建的vue单页面应用，某些特定的页面，实现前进刷新，后退不刷新，类似app般的用户体验。</p>
<p>注：　此处的刷新特指当进入此页面时，触发ajax请求，向服务器获取数据。不刷新特指当进入此页面时，不触发ajax请求，而是使用之前缓存的数据，以便减少服务器请求，用户体验更流畅。</p>
</blockquote>
<a id="more"></a>
<h4 id="1-在app-vue中改写router-view"><a href="#1-在app-vue中改写router-view" class="headerlink" title="1.在app.vue中改写router-view"></a>1.在app.vue中改写router-view</h4><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">keep-alive</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-view</span> <span class="attr">v-if</span>=<span class="string">"$route.meta.keepAlive"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 这里是会被缓存的视图组件 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">keep-alive</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;<span class="name">router-view</span> <span class="attr">v-if</span>=<span class="string">"!$route.meta.keepAlive"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 这里是不被缓存的视图组件 --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2-在router-index-js中添加路由元信息，设置需要缓存的页面"><a href="#2-在router-index-js中添加路由元信息，设置需要缓存的页面" class="headerlink" title="2.在router/index.js中添加路由元信息，设置需要缓存的页面"></a>2.在router/index.js中添加<a href="https://router.vuejs.org/zh-cn/advanced/meta.html" target="_blank" rel="noopener">路由元信息</a>，设置需要缓存的页面</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">routes: [&#123;</span><br><span class="line">        path: <span class="string">'/'</span>,</span><br><span class="line">        name: <span class="string">'index'</span>,</span><br><span class="line">        component: index,</span><br><span class="line">        meta: &#123;</span><br><span class="line">            keepAlive: <span class="literal">false</span>, <span class="comment">//此组件不需要被缓存</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        path: <span class="string">'/page1'</span>,</span><br><span class="line">        name: <span class="string">'page1'</span>,</span><br><span class="line">        component: page1,</span><br><span class="line">        meta: &#123;</span><br><span class="line">            keepAlive: <span class="literal">true</span>, <span class="comment">//此组件需要被缓存</span></span><br><span class="line">            </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        path: <span class="string">'/page2'</span>,</span><br><span class="line">        name: <span class="string">'page2'</span>,</span><br><span class="line">        component: page2,</span><br><span class="line">        meta: &#123;</span><br><span class="line">              keepAlive: <span class="literal">true</span>, <span class="comment">// 此组件需要被缓存</span></span><br><span class="line">              isBack:<span class="literal">false</span>, <span class="comment">//用于判断上一个页面是哪个</span></span><br><span class="line">          &#125;</span><br><span class="line"></span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        path: <span class="string">'/page3'</span>,</span><br><span class="line">        name: <span class="string">'page3'</span>,</span><br><span class="line">        component: page3,</span><br><span class="line">        meta: &#123;</span><br><span class="line">            keepAlive: <span class="literal">false</span>, <span class="comment">// 此组件不需要被缓存</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<h4 id="3-beforeRouteEnter中判断是从哪个页面过来的"><a href="#3-beforeRouteEnter中判断是从哪个页面过来的" class="headerlink" title="3.beforeRouteEnter中判断是从哪个页面过来的"></a>3.beforeRouteEnter中判断是从哪个页面过来的</h4><blockquote>
<p>判断是从哪个路由过来的，如果是page2过来的，表明当前页面不需要刷新获取新数据，直接用之前缓存的数据即可</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">beforeRouteEnter(to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">  <span class="comment">// 路由导航钩子，此时还不能获取组件实例 `this`，所以无法在data中定义变量（利用vm除外）</span></span><br><span class="line">  <span class="comment">// 参考 https://router.vuejs.org/zh-cn/advanced/navigation-guards.html</span></span><br><span class="line">  <span class="comment">// 所以，利用路由元信息中的meta字段设置变量，方便在各个位置获取。这就是为什么在meta中定义isBack</span></span><br><span class="line">  <span class="comment">// 参考 https://router.vuejs.org/zh-cn/advanced/meta.html</span></span><br><span class="line">  <span class="keyword">if</span>(<span class="keyword">from</span>.name==<span class="string">'page2'</span>)&#123;</span><br><span class="line">      to.meta.keepAlive=<span class="literal">true</span>;</span><br><span class="line">      <span class="comment">//判断是从哪个路由过来的，</span></span><br><span class="line">      <span class="comment">//如果是page2过来的，表明当前页面不需要刷新获取新数据，直接用之前缓存的数据即可</span></span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  next();</span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>

<h5 id="钩子函数的执行顺序"><a href="#钩子函数的执行顺序" class="headerlink" title="钩子函数的执行顺序"></a>钩子函数的执行顺序</h5><ul>
<li>不使用keep-alive</li>
</ul>
<blockquote>
<p>beforeRouteEnter –&gt; created –&gt; mounted –&gt; destroyed</p>
</blockquote>
<ul>
<li>使用keep-alive</li>
</ul>
<blockquote>
<p>beforeRouteEnter –&gt; created –&gt; mounted –&gt; activated –&gt; deactivated<br>再次进入缓存的页面，只会触发beforeRouteEnter –&gt;activated –&gt; deactivated 。created和mounted不会再执行。我们可以利用不同的钩子函数，做不同的事。务必理解上述钩子函数的执行时机和执行顺序，本教程的核心就依赖于此钩子函数</p>
</blockquote>
<h6 id="activated和deactivated是使用keep-alive后，vue中比较重要的两个钩子函数，建议详细了解下。"><a href="#activated和deactivated是使用keep-alive后，vue中比较重要的两个钩子函数，建议详细了解下。" class="headerlink" title="activated和deactivated是使用keep-alive后，vue中比较重要的两个钩子函数，建议详细了解下。"></a>activated和deactivated是使用keep-alive后，vue中比较重要的两个钩子函数，建议详细了解下。</h6><h4 id="4-activated中执行getData这个获取数据的方法"><a href="#4-activated中执行getData这个获取数据的方法" class="headerlink" title="4.activated中执行getData这个获取数据的方法"></a>4.activated中执行getData这个获取数据的方法</h4><blockquote>
<p>因为这个页面需要缓存。只有第一次进入时才会执行created和mounted方法，再次进入就不执行了。而activated每次进入都执行，所以在这个钩子函数中获取数据。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">activated() &#123;</span><br><span class="line">  <span class="keyword">if</span>(!<span class="keyword">this</span>.$route.meta.isBack)&#123;</span><br><span class="line">    <span class="comment">// 如果isBack是false，表明需要获取新数据，否则就不再请求，直接使用缓存的数据</span></span><br><span class="line">    <span class="keyword">this</span>.getData();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 恢复成默认的false，避免isBack一直是true，导致下次无法获取数据</span></span><br><span class="line">  <span class="keyword">this</span>.$route.meta.isBack=<span class="literal">false</span></span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a href="https://blog.csdn.net/qq_40963664/article/details/80062130" target="_blank" rel="noopener">参考链接</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="wgjh5.github.io/2019/08/07/keepAlive使用方法/" data-id="cjzdy95tz0005acu81l8oxgos"
         class="article-share-link">分享</a>
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vue/">vue</a></li></ul>

    </footer>

  </div>

  
    
  <nav class="article-nav">
    
      <a href="/2019/08/07/localStorage和sessionStorage的监听/" class="article-nav-link">
        <strong class="article-nav-caption">前一篇</strong>
        <div class="article-nav-title">
          
            localStorage和sessionStorage的监听
          
        </div>
      </a>
    
    
      <a href="/2019/08/07/git/" class="article-nav-link">
        <strong class="article-nav-caption">后一篇</strong>
        <div class="article-nav-title">创建github账户</div>
      </a>
    
  </nav>


  

  
    
    <div class="gitalk" id="gitalk-container"></div>
    <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
        <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
            <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
                <script type="text/javascript">
                    var gitalk = new Gitalk({
                        clientID: '64ce5333a42f02cf200d',
                        clientSecret: '7d37a3d8d3c9e215de06d3078bd1894053368739',
                        repo: 'wgjh5.github.io',
                        owner: 'wgjh5',
                        admin: ['wgjh5'],
                        // id: location.pathname,      // Ensure uniqueness and length less than 50
                        id: md5(location.pathname),
                        distractionFreeMode: true, // Facebook-like distraction free mode
                        pagerDirection: 'last'
                    })

                    gitalk.render('gitalk-container')
                </script>
                
  

</article>



</section>
                <footer class="footer">
  <div class="outer">
    <div class="float-right">
      <ul class="list-inline">
  
    <li><i class="fe fe-smile-alt"></i> <span id="busuanzi_value_site_uv"></span></li>
  
</ul>
    </div>
    <ul class="list-inline">
      <li>&copy; 2019 一只正在成长的程序猿</li>
      <li>Powered by <a href="http://hexo.io/" target="_blank">Hexo</a></li>
      <li>Theme  <a href="https://github.com/zhwangart/hexo-theme-ocean">Ocean</a></li>
    </ul>
  </div>
</footer>

        </main>
        <aside class="sidebar">
            <button class="navbar-toggle"></button>

<nav class="navbar">
  
    <div class="logo">
      <a href="/"><img src="/images/shark.svg" alt="一只正在成长的程序猿"></a>
    </div>
  
  <ul class="nav nav-main">
    
      <li class="nav-item">
        <a class="nav-item-link" href="/">主页</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/archives">归档</a>
      </li>
    
      <li class="nav-item">
        <a class="nav-item-link" href="/about">关于</a>
      </li>
    
    <li class="nav-item">
      <a class="nav-item-link nav-item-search" title="搜索">
        <i class="fe fe-search"></i>
        搜索
      </a>
    </li>
  </ul>
</nav>

<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      <div class="totop" id="totop">
  <i class="fe fe-rocket"></i>
</div>
    </li>
    <li class="nav-item">
      
        <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
          <i class="fe fe-feed"></i>
        </a>
      
    </li>
  </ul>
</nav>

<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
        </aside>
        <script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/lazyload.min.js"></script>
<script src="/js/snap.svg-min.js"></script>
<script src="/js/busuanzi-2.3.pure.min.js"></script>


  <script src="/fancybox/jquery.fancybox.min.js"></script>



  <script src="/js/search.js"></script>


<script src="/js/ocean.js"></script>

    </body>

    </html>